//# sourceURL=bigscreen.js
/**
 * Created by lhassy on 2016/12/28.
 */
var bigscreen = function () {

    var setIntervalID = 0;
    var fontcolor = "white";

    function GetET() {
        $.ajax({
            type: "POST",
            url: backServerUrl + "api/auth/token",
            dataType: "json",
            headers: {'Content-Type': 'application/json'},
            success: function (data) {

            },
            error: function () {

            }
        });
    }
    //借书排行榜 3
    function BorrowCount() {
        var et = window.localStorage["et"];
        var backServerUrl = window.localStorage["backServerUrl"];
        var now = new Date().format("yyyy-MM-dd");
        var startTime = "2017-01-01";
        var endTime = now;
        var limit = 10;
        $.ajax({
            type: "get",
            url: backServerUrl + "api/statistics/jh?start=" + startTime + "T00:00:01.001&end=" + endTime + "T23:59:59.001&interval=1m&top=" + limit  + "&device_alias=&source=false&aggregation=operation__book_name",
            dataType: "json",
            headers: {'Content-Type': 'application/json', 'Authorization': et},
            beforeSend: function(){
                // $("#countreportbutton").addClass("breath_light");
            },
            complete: function(){
                // $("#countreportbutton").removeClass("breath_light");
            },
            success: function (data) {
                var bu = null;
                var tableCount = "";
                //按书名
                for (var i in data.aggregations.operation.buckets) {
                    if (data.aggregations.operation.buckets[i].key === "borrow")
                        bu = data.aggregations.operation.buckets[i].book_name.buckets;
                }
                if (bu == null) {
                    alert("该段时间内没有数据!");
                    return;
                }
                tableCount += "<table id='tablecountlocation' border='1px' cellpadding='0' cellspacing='0' bordercolor='cadetblue' style='width:50%; border:solid 1px cadetblue; background-color: rgba(151, 217, 219, 0.22); border-collapse:collapse; font-size: 20px; margin: auto;'><thead><tr style='background-color: cadetblue; color: white;'><th>图书名称</th><th style='text-align: right;'>借阅次数</th></tr></thead><tbody>";
                for (var i in bu) {
                    tableCount += "<tr><th>" + bu[i].key + "</th><td style='text-align: right;'>" + bu[i].doc_count + "</td></tr>";
                }
                tableCount += "</tbody></table>";

                $("#tableborrow").append(tableCount);

                //按书名
                $('#chartborrow').highcharts({
                    data: {
                        table: 'tablecountlocation'
                    },
                    colors: ['#9C8045', '#50B432', '#DDDF00'],
                    chart: {
                        type: 'area',
                        // options3d: {
                        //    enabled: true,
                        //    alpha: 2,
                        //    beta: 2,
                        //    viewDistance: 25,
                        //    depth: 20
                        // },
                        backgroundColor: 'rgba(0,0,0,0)'
                    },
                    credits: {
                        enabled: false
                    },
                    title: {
                        text: '借阅排行榜',
                        style:{
                            'fontSize':'18px',
                            'color':fontcolor
                        }
                    },
                    legend:{
                        enabled : false
                    },
                    xAxis:{
                        labels:{
                            style:{
                                'color':fontcolor
                            }
                        }
                    },
                    yAxis: {
                        allowDecimals: false,
                        gridLineWidth: 0,
                        title: {
                            text: '借阅次数',
                            style:{
                                'fontSize':'18px',
                                'color':fontcolor
                            }
                        },
                        labels:{
                            style:{
                                'color':fontcolor
                            }
                        }
                    },
                    plotOptions: {
                        area: {
                            fillColor: {
                                linearGradient: {
                                    x1: 0,
                                    y1: 0,
                                    x2: 0,
                                    y2: 1
                                },
                                stops: [
                                    [0, Highcharts.getOptions().colors[2]],
                                    [1, Highcharts.Color(Highcharts.getOptions().colors[2]).setOpacity(0).get('rgba')]
                                ]
                            },
                            marker: {
                                radius: 2
                            },
                            lineWidth: 1,
                            states: {
                                hover: {
                                    lineWidth: 1
                                }
                            },
                            threshold: null
                        }
                        // series: {
                        //     borderWidth: 0,
                        //     colorByPoint: true,
                        //     dataLabels: {
                        //         enabled: true,
                        //         format: '{point.y}',
                        //         style:{
                        //             'color':fontcolor
                        //         }
                        //     }
                        // }
                    },
                    exporting: { enabled: false },
                    tooltip: {
                        formatter: function () {
                            return '<b>' + this.series.name + '</b><br/>' + this.point.y + ' ' + this.point.name.toLowerCase();
                        }
                    }
                });
            }
        });
    }
    //读者排行榜
    function ReaderCount() {
        var et = window.localStorage["et"];
        var backServerUrl = window.localStorage["backServerUrl"];
        var startTime = "2016-07-11";
        var endTime = "2016-08-20";
        var limit = 10;
        $.ajax({
            type: "get",
            url: backServerUrl + "api/statistics/jh?start=" + startTime + "T00:00:01.001&end=" + endTime + "T23:59:59.001&interval=1m&top=" + limit + "&device_alias=&source=false&aggregation=operation__reader_name",
            dataType: "json",
            headers: {'Content-Type': 'application/json', 'Authorization': et},
            beforeSend: function(){
                // $("#countreportbutton").addClass("breath_light");
            },
            complete: function(){
                // $("#countreportbutton").removeClass("breath_light");
            },
            success: function (data) {
                var tableCount = "";
                var bu = null;

                //按读者
                var xCategories = [];
                var borrowData = [];

                    for (var i in data.aggregations.operation.buckets) {
                        if (data.aggregations.operation.buckets[i].key === "borrow")
                            bu = data.aggregations.operation.buckets[i].reader_id.buckets;
                    }
                    if (bu == null) {
                        alert("该段时间内没有数据!");
                        return;
                    }
                    // tableCount += "<input id='buttoncountprintsuccess' type='button' value='打印表格' onclick='PrintCountTable(tablecountlocation,\"读者排行榜\");' style='margin-left: 30px;'/>";
                    // tableCount += "<div id='count_chart_location' style='width: 90%; margin: auto;'>统计图表</div>";
                    // tableCount += "<table id='tablecountreader' border='1px' cellpadding='0' cellspacing='0' bordercolor='cadetblue' style='width:500px; border:solid 1px cadetblue; background-color: rgba(151, 217, 219, 0.22); border-collapse:collapse; font-size: 20px; margin: auto;'><thead><tr style='background-color: cadetblue; color: white;'><th>读者ID</th><th>读者姓名</th><th style='text-align: right;'>借阅次数</th></tr></thead><tbody>";
                    for (var i in bu) {
                        xCategories.push(bu[i].reader_name.hits.hits[0]._source.reader_name);
                        borrowData.push(bu[i].doc_count);
                        // tableCount += "<tr><td>" + bu[i].key + "</td><td>" + bu[i].reader_name.hits.hits[0]._source.reader_name + "</td><td style='text-align: right;'>" + bu[i].doc_count + "</td></tr>";
                    }
                    // tableCount += "</tbody></table>";
                // $("#tablereader").append(tableCount);

                //按读者
                $('#chartreader').highcharts({
                    colors: ['#4568D9', '#7FB451', '#DDDF00'],
                    chart: {
                        type: 'column',
                        // options3d: {
                        //     enabled: true,
                        //     alpha: 2,
                        //     beta: 2,
                        //     viewDistance: 25,
                        //     depth: 20
                        // },
                        backgroundColor: 'rgba(0,0,0,0)'
                    },
                    credits: {
                        enabled: false
                    },
                    title: {
                        text: '读者排行榜',
                        style:{
                            'fontSize':'18px',
                            'color':fontcolor
                        }
                    },
                    legend:{
                        enabled : false
                    },
                    exporting: { enabled: false },
                    xAxis: {
                        categories: xCategories,
                        labels:{
                            style:{
                                'color':fontcolor
                            }
                        }
                    },
                    yAxis: {
                        allowDecimals: false,
                        title: {
                            text: '借阅次数',
                            style:{
                                'fontSize':'18px',
                                'color':fontcolor
                            }
                        },
                        labels:{
                            style:{
                                'color':fontcolor
                            }
                        }
                    },
                    plotOptions: {
                        series: {
                            borderWidth: 0,
                            colorByPoint: true,
                            dataLabels: {
                                enabled: true,
                                format: '{point.y}',
                                style:{
                                    'color':fontcolor
                                }
                            }
                        }
                    },
                    // exporting: { enabled: false },
                    series: [{
                        name: '借阅次数',
                        data: borrowData
                    }]
                });
            }
        });
    }
    //借书还书柱状图 5
    function BRDisplay() {
        var et = window.localStorage["et"];
        var backServerUrl = window.localStorage["backServerUrl"];
        var now = new Date().format("yyyy-MM-dd");
        var startTime = now;
        var endTime = now;
        var interval = "1h";
        $.ajax({
            type: "get",
            url: backServerUrl + "api/statistics/jh?start=" + startTime + "T00:00:00.001&end=" + endTime + "T23:59:59.001&interval=" + interval + "&device_alias=&source=false&aggregation=operation__datetime",
            dataType: "json",
            headers: {'Content-Type': 'application/json','Authorization':et},
            success: function (data) {

                var tableCount = "";
                var sfdata = null;
                var dhdata = "";
                var xCategories = [];
                var returnData = [];
                var borrowData = [];
                var renewData = [];
                var countDeviceHeader = "";
                if ($("#selectdevicebutton").prop("checked")) {
                    var dh = data.aggregations.device.buckets;
                    for (var i in dh) {
                        countDeviceHeader += "<th style='text-align: right;'>" + deviceAliasToLocationMap[dh[i].key] + "</th>";
                    }
                }

                //按日期
                //tableCount += "<input id='buttoncountdate' type='button' value='显示表格' onclick='ShowCountTable(\"tablecountdate\");' style='margin-left: 100px;'/>";
                tableCount += "<input id='buttoncountprintsuccess' type='button' value='打印表格' onclick='PrintCountTable(tablecountdate,\"流通统计(按日期)\");' style='margin-left: 100px;'/>";
                tableCount += "<div id='count_chart_date' style='width: 90%; margin: auto;'>统计图表</div>";
                tableCount += "<table id='tablecountdate' border='1px' cellpadding='0' cellspacing='0' bordercolor='cadetblue' style='width:380px; border:solid 1px cadetblue; background-color: rgba(151, 217, 219, 0.22); border-collapse:collapse; font-size: 20px; margin: auto auto 30px;'><thead><tr style='background-color: cadetblue; color: white;'><th>日期</th>";
                var bu = data.aggregations.operation.buckets;

                var theadBorrow = "";
                var theadReturn = "";
                var theadRenew = "";
                for (var i in bu) {
                    if (bu[i].key === "return")
                        theadReturn = "<th style='text-align: right;'>还书数量</th>";
                    else if (bu[i].key === "borrow")
                        theadBorrow = "<th style='text-align: right;'>借书数量</th>";
                    else if (bu[i].key === "renew")
                        theadRenew = "<th style='text-align: right;'>续借数量</th>";
                }
                tableCount += theadBorrow + theadReturn + theadRenew;


                tableCount += "</tr></thead><tbody>";
                if (bu.length > 0) {
                    var jh = "";
                    var jhstime = "";
                    var jhetime = "";
                    for (var i in bu[0].datetime.buckets) {
                        if(interval === "5min") {
                            xCategories.push(bu[0].datetime.buckets[i].key_as_string.substring(11, 16));
                        }
                        if(interval === "1h") {
                            xCategories.push(bu[0].datetime.buckets[i].key_as_string.substring(11, 16));
                        }
                        var tdataBorrow = "";
                        var tdataReturn = "";
                        var tdataRenew = "";
                        for (var j = 0; j < bu.length; j++) {
                            switch (bu[j].key){
                                case "borrow":
                                    borrowData.push(bu[j].datetime.buckets[i].doc_count);
                                    // tdataBorrow = "<td style='text-align: right;'><a href='javascript:void(0);' onclick='DisplayJHDetails(\"" + jhstime + "\",\"" + jhetime + "\",\"" + selectedDevice + "\",\"\",\"\",\"" + bu[j].key + "\",\"\");'>" + bu[j].datetime.buckets[i].doc_count + "</a></td>";
                                    break;
                                case "return":
                                    returnData.push(-bu[j].datetime.buckets[i].doc_count);
                                    // tdataReturn = "<td style='text-align: right;'><a href='javascript:void(0);' onclick='DisplayJHDetails(\"" + jhstime + "\",\"" + jhetime + "\",\"" + selectedDevice + "\",\"\",\"\",\"" + bu[j].key + "\",\"\");'>" + bu[j].datetime.buckets[i].doc_count + "</a></td>";
                                    break;
                                case "renew":
                                    renewData.push(bu[j].datetime.buckets[i].doc_count);
                                    // tdataRenew = "<td style='text-align: right;'><a href='javascript:void(0);' onclick='DisplayJHDetails(\"" + jhstime + "\",\"" + jhetime + "\",\"" + selectedDevice + "\",\"\",\"\",\"" + bu[j].key + "\",\"\");'>" + bu[j].datetime.buckets[i].doc_count + "</a></td>";
                                    break;
                            }
                        }
                    }
                }


                // $("div[id^='count_chart']").remove();
                // $("table[id^='tablecount']").remove();
                //
                // $("input[id^='buttoncount']").remove();
                // $("label[name^='devicecountlabel']").remove();
                // $("input[name='devicecountradio']").remove();
                // $("#content").append(tableCount);

                $('#chartreader').highcharts({
                    //data: {
                    //    table: 'tablecountdate'
                    //},
                    colors: ['#D9D762', '#B47944', '#DDDF00'],
                    chart: {
                        type: 'column',
                        // options3d: {
                        //     enabled: true,
                        //     alpha: 2,
                        //     beta: 2,
                        //     viewDistance: 25,
                        //     depth: 20
                        // },
                        backgroundColor: 'rgba(0,0,0,0)'
                    },
                    credits: {
                        enabled: false
                    },
                    title: {
                        text: ''
                    },
                    xAxis: {
                        // enabled:false,
                        categories:xCategories,
                        reversed: false,
                        //type: 'datetime',
                        labels: {
                            // enabled:false,
                            // step: 1,
                            // rotation: 30
                            style:{
                                'color':fontcolor
                            }
                        }
                    },
                    yAxis: {
                        allowDecimals: false,
                        gridLineWidth: 0,
                        title: {
                            text: ''
                        },
                        labels:{
                            enabled:true,
                            style:{
                                'color':fontcolor
                            }
                        }
                    },
                    legend:{
                        enabled : true,
                        itemStyle:{
                            'color':fontcolor
                        }
                    },
                    exporting: { enabled: false },
                    plotOptions: {
                        series: {
                            marker:{
                                enabled:false
                            },
                            stacking: 'normal',
                            borderWidth: 0,
                            dataLabels: {
                                // enabled: false,
                                // format: '{point.y}'
                                formatter: function () {
                                    // if(this.value !== 0)
                                        return this.y;
                                }
                            }
                        }
                    },
                    series: [{
                        name: '借书数量',
                        data: borrowData
                    }, {
                        name: '还书数量',
                        data: returnData
                    }]
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                //当前状态(readyState),0-未初始化，1-正在载入，2-已经载入，3-数据进行交互，4-完成
                console.log("PaperCount 请求产生错误!\n" + "status = " + XMLHttpRequest.status + "\nstatusText = " + XMLHttpRequest.statusText + "\nreadyState = " + XMLHttpRequest.readyState + "\nresponseText = " + XMLHttpRequest.responseText);
            }
        });
    }
    //借还总册次 6
    function BRCount() {
        var et = window.localStorage["et"];
        var backServerUrl = window.localStorage["backServerUrl"];
        var now = new Date().format("yyyy-MM-dd");
        var startTime = "2017-01-01";
        var endTime = now;
        var interval = "1y";
        $.ajax({
            type: "get",
            url: backServerUrl + "api/statistics/jh?start=" + startTime + "T00:00:00.001&end=" + endTime + "T23:59:59.001&interval=" + interval + "&device_alias=&source=false&aggregation=operation__datetime",
            dataType: "json",
            headers: {'Content-Type': 'application/json','Authorization':et},
            success: function (data) {
                var tableCount = "";
                var sfdata = null;
                var dhdata = "";
                var xCategories = [];
                var returnData = [];
                var borrowData = [];
                var renewData = [];
                var countDeviceHeader = "";
                // if ($("#selectdevicebutton").prop("checked")) {
                //     var dh = data.aggregations.device.buckets;
                //     for (var i in dh) {
                //         countDeviceHeader += "<th style='text-align: right;'>" + deviceAliasToLocationMap[dh[i].key] + "</th>";
                //     }
                // }

                //按日期
                //tableCount += "<input id='buttoncountdate' type='button' value='显示表格' onclick='ShowCountTable(\"tablecountdate\");' style='margin-left: 100px;'/>";
                // tableCount += "<input id='buttoncountprintsuccess' type='button' value='打印表格' onclick='PrintCountTable(tablecountdate,\"流通统计(按日期)\");' style='margin-left: 100px;'/>";
                // tableCount += "<div id='count_chart_date' style='width: 90%; margin: auto;'>统计图表</div>";
                // tableCount += "<table id='tablecountdate' border='1px' cellpadding='0' cellspacing='0' bordercolor='cadetblue' style='width:380px; border:solid 1px cadetblue; background-color: rgba(151, 217, 219, 0.22); border-collapse:collapse; font-size: 20px; margin: auto auto 30px;'><thead><tr style='background-color: cadetblue; color: white;'><th>日期</th>";
                var bu = data.aggregations.operation.buckets;

                // var theadBorrow = "";
                // var theadReturn = "";
                // var theadRenew = "";
                // for (var i in bu) {
                //     if (bu[i].key === "return")
                //         theadReturn = "<th style='text-align: right;'>还书数量</th>";
                //     else if (bu[i].key === "borrow")
                //         theadBorrow = "<th style='text-align: right;'>借书数量</th>";
                //     else if (bu[i].key === "renew")
                //         theadRenew = "<th style='text-align: right;'>续借数量</th>";
                // }
                // tableCount += theadBorrow + theadReturn + theadRenew;


                // tableCount += "</tr></thead><tbody>";
                if (bu.length > 0) {
                    var jh = "";
                    var jhstime = "";
                    var jhetime = "";
                    for (var i in bu[0].datetime.buckets) {
                        // if(interval === "5min") {
                        //     xCategories.push(bu[0].datetime.buckets[i].key_as_string.substring(11, 16));
                        // }
                        // if(interval === "1h") {
                        //     xCategories.push(bu[0].datetime.buckets[i].key_as_string.substring(11, 16));
                        // }
                        var tdataBorrow = "";
                        var tdataReturn = "";
                        var tdataRenew = "";
                        var countBorrow = 0;
                        var countReturn = 0;
                        for (var j = 0; j < bu.length; j++) {
                            switch (bu[j].key){
                                case "borrow":
                                    // borrowData.push(bu[j].datetime.buckets[i].doc_count);
                                    countBorrow += bu[j].datetime.buckets[i].doc_count;
                                    // tdataBorrow = "<td style='text-align: right;'><a href='javascript:void(0);' onclick='DisplayJHDetails(\"" + jhstime + "\",\"" + jhetime + "\",\"" + selectedDevice + "\",\"\",\"\",\"" + bu[j].key + "\",\"\");'>" + bu[j].datetime.buckets[i].doc_count + "</a></td>";
                                    break;
                                case "return":
                                    // returnData.push(-bu[j].datetime.buckets[i].doc_count);
                                    countReturn += bu[j].datetime.buckets[i].doc_count;
                                    // tdataReturn = "<td style='text-align: right;'><a href='javascript:void(0);' onclick='DisplayJHDetails(\"" + jhstime + "\",\"" + jhetime + "\",\"" + selectedDevice + "\",\"\",\"\",\"" + bu[j].key + "\",\"\");'>" + bu[j].datetime.buckets[i].doc_count + "</a></td>";
                                    break;
                                case "renew":
                                    // renewData.push(bu[j].datetime.buckets[i].doc_count);
                                    // tdataRenew = "<td style='text-align: right;'><a href='javascript:void(0);' onclick='DisplayJHDetails(\"" + jhstime + "\",\"" + jhetime + "\",\"" + selectedDevice + "\",\"\",\"\",\"" + bu[j].key + "\",\"\");'>" + bu[j].datetime.buckets[i].doc_count + "</a></td>";
                                    break;
                            }
                        }
                    }
                    $(".countborrow").html(countBorrow);
                    $(".countreturn").html(countReturn);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                //当前状态(readyState),0-未初始化，1-正在载入，2-已经载入，3-数据进行交互，4-完成
                alert("PaperCount 请求产生错误!\n" + "status = " + XMLHttpRequest.status + "\nstatusText = " + XMLHttpRequest.statusText + "\nreadyState = " + XMLHttpRequest.readyState + "\nresponseText = " + XMLHttpRequest.responseText);
            }
        });
    }

    function CategoryDisplay() {
        var colors = Highcharts.getOptions().colors;
        var categories = ['文学', '艺术', '文化、科学、教育', '历史、地理', '其他'];
        var data = [{
            y: 55.11,
            color: "#4D33CC",
            fontSize:'20px',
            style: {     fontSize:"18px",    color :'red'  },
            drilldown: {
                name: '文学',
                categories: ['小说', '儿童文学', '散文'],
                data: [33.06,15.85, 5.16],
                fontSize:'20px',
                style: {     fontSize:"18px",    color :'red'  },
                color: "#4D33CC"
            }
        }, {
            y: 21.63,
            color: "#1F1F1F",
            drilldown: {
                name: '艺术',
                categories: ['书法', '绘画技法', '绘画研究方法', '中国绘画作品'],
                data: [1.03, 1.58, 10.12, 8.43],
                color: "#1F1F1F"
            }
        }, {
            y: 11.94,
            color: "#1A9900",
            drilldown: {
                name: '文化、科学、教育',
                categories: ['中等教育', '文体活动', '学前教育', '初等教育'],
                data: [2.36, 5.32, 5.91, 2.15],
                color: "#1A9900"
            }
        }, {
            y: 7.15,
            color: "#FF6600",
            drilldown: {
                name: '历史、地理',
                categories: ['通史', '中国地理', '隋唐至清前期', '封建社会'],
                data: [4.55, 1.42, 0.64, 0.33],
                color: "#FF6600"
            }
        }, {
            y: 2.14,
            color: "#9933CC",
            drilldown: {
                name: '其他',
                categories: ['其他'],
                data: [ 2.54],
                color: "#9933CC"
            }
        }];
        var browserData = [];
        var versionsData = [];
        var i, j;
        var dataLen = data.length;
        var drillDataLen;
        var brightness;
        // Build the data arrays
        for (i = 0; i < dataLen; i += 1) {
            // add browser data
            browserData.push({
                name: categories[i],
                y: data[i].y,
                color: data[i].color
            });

            // add version data
            drillDataLen = data[i].drilldown.data.length;
            for (j = 0; j < drillDataLen; j += 1) {
                brightness = 0.2 - (j / drillDataLen) / 5;
                versionsData.push({
                    name: data[i].drilldown.categories[j],
                    y: data[i].drilldown.data[j],
                    color: Highcharts.Color(data[i].color).brighten(brightness).get()
                });
            }
        }

        var chart = {
            type: 'pie',
            backgroundColor: 'rgba(0,0,0,0)',
            labels: {                  //图表标签

            }
        };
        var title = {
            text: ''
        };
        var yAxis = {
            title: {
                text: ''
            }
        };
        var series= [{
            name: 'Browsers',
            data: browserData,
            size: '60%',
            dataLabels: {
                formatter: function () {
                    return this.y > 5 ? this.point.name : null;
                },
                color: 'white',
                style: {    textShadow:''  },
                distance: -30
            }
        }, {
            name: 'Versions',
            data: versionsData,
            size: '80%',
            innerSize: '60%',
            dataLabels: {
                color: 'white',
                style: {    textShadow:''  },
                formatter: function () {
                    // display only if larger than 1
                    return this.y > 1 ? '' + this.point.name + ': ' + this.y + '%'  : null;
                }
            }
        }
        ];
        var exp =  {
            enabled:false
        };
        var credits = {
            enabled:false
        }
        var json = {};
        json.chart = chart;
        json.title = title;
        json.yAxis = yAxis;
        json.exporting = exp;
        json.series = series;
        json.credits = credits;
        $('#chartCategory').highcharts(json);
    }

    function getLastDay(year,month) {
        var new_year = year;    //取当前的年份
        var new_month = month++;//取下一个月的第一天，方便计算（最后一天不固定）
        if(month>12) {
            new_month -=12;        //月份减
            new_year++;            //年份增
        }
        var new_date = new Date(new_year,new_month,1);                //取当年当月中的第一天
        return (new Date(new_date.getTime()-1000*60*60*24)).getDate();//获取当月最后一天日期
    }
    //入馆人数柱状图 4
    function FlowCount() {
        var et = window.localStorage["et"];
        var backServerUrl = window.localStorage["backServerUrl"];
        // var now = new Date().format("yyyy-MM-dd");
        var year = new Date().format("yyyy");
        var month = new Date().format("MM");
        var startTime = year + "-" + month + "-01";
        var endTime = year + "-" + month + "-" + getLastDay(year, month);
        var interval = "1d";
        $.ajax({
            type: "get",
            url: backServerUrl + "api/statistics/mjflow?start=" + startTime + "T00:00:00.001&end=" + endTime + "T23:59:59.001&interval=" + interval + "&device_alias=&source=false&aggregation=datetime",
            dataType: "json",
            headers: {'Content-Type': 'application/json','Authorization':et},
            success: function (data) {

                var tableCount = "";
                var sfdata = null;
                var dhdata = "";
                var xCategories = [];
                var inData = [];
                var bu = data.aggregations.datetime.buckets;

                if (bu.length > 0) {
                    bu.forEach(function (o) {
                        xCategories.push(o.key_as_string.substring(5, 10));
                        inData.push(o.in.value);
                    });
                }

                var myChart = echarts.init(document.getElementById('flowchart'));
                // 指定图表的配置项和数据
                var option = {
                    tooltip: {},
                    legend: {
                        bottom:0,
                        data:['入馆人次'],
                        show:true,
                        textStyle:{
                            color:"#FFFFFF"
                        }
                    },
                    xAxis: {
                        axisLine:{
                            lineStyle:{
                                color:'#FFFFFF'
                            }
                        },
                        axisLabel:{
                            rotate: 40,
                            interval:'0',
                            textStyle:{
                                color:'#FFFFFF'
                            }
                        },
                        data: ["04-01","04-02","04-03","04-04","04-05","04-06","04-07","04-08","04-09","04-10","04-11","04-12","04-13","04-14","04-15","04-16","04-17","04-18","04-19","04-20","04-21","04-22","04-23","04-24","04-25","04-26","04-27","04-28","04-29","04-30"]
                    },
                    yAxis: {
                        axisLine:{
                            show:false
                        },
                        axisLabel: {
                            formatter:'{value}k',
                            textStyle: {
                                color: '#FFFFFF'
                            }
                        }
                    },
                    series: [{
                        itemStyle:{
                            normal:{
                                color:"#18ec1e"
                            }
                        },
                        name: '入馆人次',
                        type: 'bar',
                        data: [1, 2, 3, 10, 10, 20,0,0,1, 2, 3, 10, 10, 20,0,0,1, 2, 3, 10, 10, 20,0,0,1, 2, 3, 10, 10, 20]
                    }]
                };

                // 使用刚指定的配置项和数据显示图表。
                myChart.setOption(option);

                // $('#flowchart').highcharts({
                //     //data: {
                //     //    table: 'tablecountdate'
                //     //},
                //     colors: ['#18EC1E', '#B47944', '#DDDF00'],
                //     chart: {
                //         type: 'column',
                //         backgroundColor: 'rgba(0,0,0,0)'
                //     },
                //     credits: {
                //         enabled: false
                //     },
                //     title: {
                //         text: ''
                //     },
                //     xAxis: {
                //         // enabled:false,
                //         categories:xCategories,
                //         reversed: false,
                //         //type: 'datetime',
                //         labels: {
                //             // enabled:false,
                //             step: 1,
                //             rotation: -30,
                //             style:{
                //                 'color':fontcolor,
                //                 'font-weight':'bolder',
                //                 'text-shadow': '0 2px 2px #000000'
                //             }
                //         }
                //     },
                //     yAxis: {
                //         allowDecimals: false,
                //         tickPositions: [0, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000],
                //         gridLineWidth: 0,
                //         title: {
                //             text: ''
                //         },
                //         labels:{
                //             enabled:true,
                //             style:{
                //                 'color':fontcolor
                //             }
                //         }
                //     },
                //     legend:{
                //         enabled : true,
                //         itemStyle:{
                //             'color':fontcolor
                //         }
                //     },
                //     exporting: { enabled: false },
                //     plotOptions: {
                //         series: {
                //             marker:{
                //                 enabled:false
                //             },
                //             stacking: 'normal',
                //             borderWidth: 0,
                //             pointWidth: 15,
                //             dataLabels: {
                //                 // enabled: false,
                //                 // format: '{point.y}'
                //                 formatter: function () {
                //                     // if(this.value !== 0)
                //                     return this.y;
                //                 }
                //             }
                //         }
                //     },
                //     series: [{
                //         name: '入馆人次',
                //         data: inData
                //     }]
                // });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                //当前状态(readyState),0-未初始化，1-正在载入，2-已经载入，3-数据进行交互，4-完成
                console.log("PaperCount 请求产生错误!\n" + "status = " + XMLHttpRequest.status + "\nstatusText = " + XMLHttpRequest.statusText + "\nreadyState = " + XMLHttpRequest.readyState + "\nresponseText = " + XMLHttpRequest.responseText);
            }
        });
    }
    //门禁报警图书 7
    function GetMJWarn() {
        var et = window.localStorage["et"];
        var backServerUrl = window.localStorage["backServerUrl"];
        var now = new Date().format("yyyy-MM-dd");
        var startTime = now;
        var endTime = now;
        var limit = 6;
        $.ajax({
            type: "get",
            url: backServerUrl + "api/logs/mj?start=" + startTime + "T00:00:01.001&end=" + endTime + "T23:59:59.001&limit=" + limit + "",
            dataType: "json",
            headers: {'Content-Type': 'application/json', 'Authorization': et},
            success: function (data) {
                   // alert(JSON.stringify(data));
                   var mjwarnbody = "";
                   if(data.count > 0){
                       data.content.forEach(function (o) {
                           mjwarnbody += "<tr><td>" + o.gate_name + "</td><td>" + o.book_name +"</td><td>" + o.datetime.substring(0,10) +"&nbsp;" + o.datetime.substring(11,19) +"</td></tr>";
                       });
                       $("#mjwarnbody").html(mjwarnbody);
                   }
            }
        });
    }
    //门禁人数统计 4
    function GetMJFlow() {
        var et = window.localStorage["et"];
        var backServerUrl = window.localStorage["backServerUrl"];
        var now = new Date().format("yyyy-MM-dd");
        var startTime = now;
        var endTime = now;
        var limit = 10;
        $.ajax({
            type: "get",
            url: backServerUrl + "api/statistics/mjflow?aggregation=total&start=" + startTime + "T00:00:01.001&end=" + endTime + "T23:59:59.001",
            dataType: "json",
            headers: {'Content-Type': 'application/json', 'Authorization': et},
            success: function (data) {
                // alert(JSON.stringify(data));
                if(data !== undefined){
                    $("#ctotalin").html(data.total_in);
                    // $("#ctotalout").html(inlibrary);
                    var enterCount = data.in
                    if(data.in < 0)
                        enterCount = 0;
                    $("#cin").html(enterCount);
                    var inlibrary = parseInt(data.in) - parseInt(data.out);
                    if(inlibrary < 0)
                        inlibrary = 0;
                    // inlibrary = ;
                    $("#cout").html(inlibrary);
                }
            }
        });
    }
    //上月人数统计 4
    function GetMJLastMonthFlow() {
        var et = window.localStorage["et"];
        var backServerUrl = window.localStorage["backServerUrl"];
        var year = new Date().format("yyyy");
        var month = new Date().format("MM");
        if(month == "01"){
          year--;
          month = "12";
        }
        else{
          month--;
        }
        var startTime = year + "-" + month + "-01";
        var endTime = year + "-" + month + "-" + getLastDay(year, month);
        var limit = 10;
        $.ajax({
            type: "get",
            url: backServerUrl + "api/statistics/mjflow?aggregation=total&start=" + startTime + "T00:00:01.001&end=" + endTime + "T23:59:59.001",
            dataType: "json",
            headers: {'Content-Type': 'application/json', 'Authorization': et},
            success: function (data) {
                // alert(JSON.stringify(data));
                if(data !== undefined){
                    var enterCount = data.in
                    $("#lastMonthCcout").html(enterCount);
                }
            }
        });
    }
    //获取天气 2
    function GetWeather() {
        $.ajax({
            type: "get",
            url: "http://i.tianqi.com/index.php?c=code&id=83&py=beijing",
            dataType: "jsonp",
            success: function (data) {
                // alert(JSON.stringify(data));
            }
        });
    }

    function UpdateBigScreen() {
        var rootPath = getRootPath();
        var backServerUrl = "";
        if(rootPath.substring(7,10) == "192" || rootPath.substring(7,10) == "loc" || rootPath.substring(7,10) == "10.") {
           backServerUrl = "http://1.30.233.74:10000/";    //包头
           //backServerUrl = "http://10.232.2.51:10000/";    //包头内网
        }
        else
        {
            backServerUrl = "http://1.30.233.74:10000/";
        }
        window.localStorage["backServerUrl"] = backServerUrl;
        $.ajax({
            type: "POST",
            url: backServerUrl + "api/auth/token",
            dataType: "json",
            headers: {'Content-Type': 'application/json'},
            data:JSON.stringify({"username": "shrfid", "password":"111"}),
            success: function (data) {
                var last=(data.token).toString();
                // console.log(last);
                window.localStorage["et"] = "Bearer " + last;
                BorrowCount();
                BRDisplay();
                // ReaderCount();
                GetMJWarn();
                GetMJFlow();
                GetMJLastMonthFlow();
                BRCount();
                FlowCount();
                CategoryDisplay();
                var weather = '<iframe id="weather" name="weather_inc" src="http://i.tianqi.com/index.php?c=code&id=83&py=beijing" width="515" height="178" allowtransparency="true" style="background-color: transparent;" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe>';
                $("#area2").html(weather);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                //当前状态(readyState),0-未初始化，1-正在载入，2-已经载入，3-数据进行交互，4-完成
                console.log("Token 请求产生错误!\n" + "status = " + XMLHttpRequest.status + "\nstatusText = " + XMLHttpRequest.statusText + "\nreadyState = " + XMLHttpRequest.readyState + "\nresponseText = " + XMLHttpRequest.responseText);
            }
        });
    }

    function Slide() {
        slideImagesSrc = [];
        slideImagesSrc.push("book_mao.jpg");
        slideImagesSrc.push("book_3t.jpg");
        slideImagesSrc.push("book_lzyz.jpg");
        slideImagesSrc.push("book_etwx.jpg");
        $("#imgmain").attr("src", slideImagesSrc.get(0));
    }

    function InitPage() {
        $("div[id^=area]").css("border","0px solid blue");
        UpdateBigScreen();
        if(setIntervalID === 0)
            setIntervalID = setInterval("bigscreen.UpdateBigScreen()",30000);
    }

    return{
        InitPage : InitPage,
        UpdateBigScreen : UpdateBigScreen
    }
}();
